package com.freedom.ums.member.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.freedom.common.framework.exception.ServiceException;
import com.freedom.ums.member.application.service.cmd.InviteCodeCmdService;
import com.freedom.ums.member.domain.repository.MemberRepository;
import com.freedom.ums.member.domain.service.MemberService;
import com.freedom.ums.member.infrastructure.enums.RegisterEnum;
import com.freedom.ums.member.infrastructure.enums.UMSResultCodeEnum;
import com.freedom.ums.member.infrastructure.persistence.pojo.bo.MemberBO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final MemberRepository memberRepository;

    private final InviteCodeCmdService inviteCodeCmdService;

    @Override
    public void modifyStatus(List<Integer> memberIds, Integer status) {
        if (memberIds.size() < 200) {
            memberRepository.modifyStatus(memberIds, status);
        }
        List<Integer> newList = new ArrayList<>(200);
        for (Integer memberId : memberIds) {
            newList.add(memberId);
            if (newList.size() == 200) {
                memberRepository.modifyStatus(memberIds, status);
                newList.clear();
            }
        }
        if (CollUtil.isNotEmpty(newList)) {
            memberRepository.modifyStatus(memberIds, status);
        }
    }

    @Override
    public Integer memberRegister(String account, RegisterEnum registerEnum) {
        MemberBO memberBO = memberRepository.findMemberByMobile(account);
        Assert.isTrue(Objects.isNull(memberBO), () -> new ServiceException(UMSResultCodeEnum.U_ACCOUNT_EXIST));
        MemberBO member = memberBO.create(account, inviteCodeCmdService.fetchOne());
        return memberRepository.saveMember(member);
    }
}
